const REJECT = 'REJECTED';
const PENDING = 'PENDING';
const FULLFILLED = 'FULLFILLED';

function noop(v) {return v;}

class Promise {
  constructor(executor) {
    this.status = PENDING;
    console.log('被初始化了')
    this.reason = '';
    this.value = '';
    this.resolveFunctions = [];
    this.rejectFunctions = [];
    let resolve = (value) => {
      if(this.status === PENDING) {
        this.status = FULLFILLED;
        this.value = value;
<<<<<<< HEAD
        console.log('fullfilled', value)
        this.resolveFunctions.forEach(callback => {
          callback(this.value);
        })
=======
        this.resolveFunctions.forEach(fn => fn())
>>>>>>> 5aee9d9bd6cf33f6528634e89f7dbcecdda2af9e
      }
    }
    let reject = (reason) => {
      console.log('到这里来了', this.status)
      if(this.status === PENDING) {
        this.status = REJECT;
        this.reason = reason;
        this.rejectFunctions.forEach(callback => {
          callback(this.reason);
        })
      }
    }
    executor(resolve, reject);
  }
  then(success = noop, failed = noop) {
    let promise;
    // then回调时，如果promise状态已经结束了
    console.log('then', this.status)
    /**
     * promise.then(function(v1) {return v1}).then(function(v2) {return v2});
     */
    if(this.status === FULLFILLED) {
      return promise = new Promise((resolve, reject) => {
        try {
          let rv = success(this.value);
          resolve(rv);
        } catch(e) {
          reject(e);
        }
      })
    }

    if(this.status === REJECT) {
      return promise = new Promise((resolve, reject) => {
        try {
          let rjvalue = failed(this.reason);
          reject(rjvalue);
        } catch(e) {
          reject(e);
        }
      })
    }

    // 当前promise还未结束，将回调函数暂存起来
    if(this.status === PENDING) {
      console.log('结果都还在pending中')
      return promise = new Promise((resolve, reject) => {
        // 这里暂存的结果需要是一个函数
        this.resolveFunctions.push((value) => {
          try {
            let rovalue = success(value);
            resolve(rovalue);
          } catch(e) {
            reject(e);
          }
        })
        this.rejectFunctions.push((value) => {
          try {
            let rjvalue = failed(value);
            reject(rjvalue);
          } catch(e) {
            reject(e);
          }
        })
      })
    }
  }
  catch(reject) {
    if(this.status === REJECT) {
      reject(this.reason);
    }
  }
}

let pro = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve('成功')
    // reject('失败拉')
  }, 0)
})
console.log(pro)

pro.then((data) => {
  console.log('第一个then ', data);
  return '第一次回调'
}).then(data => {
<<<<<<< HEAD
  console.log('第二个then ', data);
  return  '第二次回调'
=======
  console.log('第二次回调', data);
>>>>>>> 5aee9d9bd6cf33f6528634e89f7dbcecdda2af9e
}).catch(reason => {
  console.log('出错了啊', reason);
})